/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package sp.view;

import static java.awt.Frame.ICONIFIED;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.Normalizer.Form;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JTable;
import sp.controller.ButtonController;
import sp.controller.LoginController;
import sp.controller.SaveController;
import sp.controller.SaveCtrlListing;
import sp.controller.UpdateController21;
import sp.controller.UpdatingController;
import sp.form.*;
import sp.model.*;
import sp.panelcomponent.EntryFormListingTest;
import sp.panelcomponent.EntryFormQuestTest;
import sp.util.ErrorControl;
import sp.util.FormControl;

/**
 *
 * @author Tiara Ratna Dewi [12.7403]
 */
public class TesBeta extends javax.swing.JFrame {

    /**
     * Creates new form TesBeta
     */
    LoginController controller;
    ButtonController butcontroller;

    public TesBeta() {
        initComponents();
        //icon();
        dispose();
        setUndecorated(true);
        setResizable(false);
        setVisible(true);
        setTitle("Data Entry PKL54SK");
//        try {
//            setIconImage(ImageIO.read(new FileInputStream("logo.png")));
//        } catch (IOException ex) {
//            Logger.getLogger(TesBeta.class.getName()).log(Level.SEVERE, null, ex);
//        }

        setControllerSave();
        setLoginController();
        setLoadToFormController();
        setSaveCtrlListing();
        setUpdateController();

        butcontroller = new ButtonController(this, entryQuest, entryListing, MainPanel);
        loginPanel1.getCloseminbutton1().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                System.exit(0);
            }
        });
        panel1.getCloseminbutton1().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                System.exit(0);
            }
        });
        entryQuest.getCloseminbutton1().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        entryListing.getCloseminbutton1().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        panel1.getEntryListing().getStartButton1().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                controller.show("entrylisting");
            }

        });
//        panel1.getEntryQuest().getStartButton1().addActionListener(new ActionListener() {

//            @Override
//            public void actionPerformed(ActionEvent ae) {
//                int index = panel1.getEntryQuest().getTableUpdate1().getTabelUpdate().getSelectedRow();
//                if (index > -1) {
//                    try {
//                        loadDsart2Form(index);
//                    } catch (IOException ex) {
//                        Logger.getLogger(TesBeta.class.getName()).log(Level.SEVERE, null, ex);
//                    }
//                } else {
//                    entryDariNol();
//                }
//            }
//
//            private void loadDsart2Form(int row) throws IOException {
//                sp.model.Dsartb4 db4 = ((TableEntryModel) panel1.getEntryQuest().getTableUpdate1().getTabelUpdate().getModel()).get(row);
//                String key = db4.getNuart().substring(0, db4.getNuart().length() - 2);
//                sp.model.Dsartb1 data1 = sp.dao.DsartB1Dao.getInstance().getByID(key);
//
//                if ("0".equals(data1.getIsLocked())) {
//                    changeLock(data1);
//                    sp.model.Dsartb3 data3 = sp.dao.DsartB3Dao.getInstance().getByID(key);
//                    sp.model.Dsartb4 data4 = sp.dao.DsartB4Dao.getInstance().getByID(db4.getNuart());
//                    entryQuest.getHal11().setFromListing(data1, data3, data4);
//                    entryQuest.getHal21().setFromListing(data4);
//
//                    String loadData = "";
//                    try {
//                        entryQuest.getErrorTable1().getTabelError().setModel(sp.util.ErrorControl.getTableRow());
//                    } catch (Exception e) {
//                        loadData = e.getMessage();
//                    }
//                    LogMessage.write(loadData);
//                    entryQuest.getSaveBtn().setEnabled(true);
//                    entryQuest.getUpdateBtn().setEnabled(false);
//                    controller.show("entryQuest");
//                } else {
//                    JOptionPane.showMessageDialog(entryQuest, "Sorry, data of "+db4.getNuart()+" is used by other user");
//                }
//            }
//
//            private void changeLock(Dsartb1 o) {
//                String locked = "1", unlocked = "0";
//                if (o.getIsLocked().equals(unlocked)) {
//                    o.setIsLocked(locked);
//                } else {
//                    o.setIsLocked(unlocked);
//                }
//                sp.dao.DsartB1Dao.getInstance().update(o);
//            }
//        });
        panel1.getMinimizebutton1().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                setState(ICONIFIED);
            }
        });
        loginPanel1.getMinimizebutton1().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                setState(ICONIFIED);
            }
        });
        entryQuest.getMinimizebutton1().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                setState(ICONIFIED);
            }
        });
        entryListing.getMinimizebutton1().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                setState(ICONIFIED);
            }
        });
    }

    public JPanel getMainPanel() {
        return MainPanel;
    }

    public EntryFormListingTest getEntryListing() {
        return entryListing;
    }

    public EntryFormQuestTest getEntryQuest() {
        return entryQuest;
    }

    public LoginPanel getLoginPanel1() {
        return loginPanel1;
    }

    public Panel getPanel1() {
        return panel1;
    }

//    public void icon() {
//        ImageIcon ico = new ImageIcon("src/image/logo.png");
//        setIconImage(ico.getImage());
//    }

    protected static ImageIcon createImageIcon(String path) {
// Ganti IconFrame dengan nama kelas jFrame Anda
        java.net.URL imgURL = Form.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn’t find file:" + path);
            return null;
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        MainPanel = new javax.swing.JPanel();
        loginPanel1 = new sp.view.LoginPanel();
        panel1 = new sp.view.Panel();
        entryQuest = new sp.panelcomponent.EntryFormQuestTest();
        entryListing = new sp.panelcomponent.EntryFormListingTest();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        MainPanel.setLayout(new java.awt.CardLayout());
        MainPanel.add(loginPanel1, "login");
        MainPanel.add(panel1, "panel");
        MainPanel.add(entryQuest, "entryquest");
        MainPanel.add(entryListing, "entrylisting");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(MainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(MainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        Image oldIcon = getIconImage();
        ImageIcon newIcon = createImageIcon("/sp/image/logo.png");
        setIconImage(newIcon.getImage());
    }//GEN-LAST:event_formWindowActivated

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TesBeta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TesBeta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TesBeta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TesBeta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TesBeta().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel MainPanel;
    private sp.panelcomponent.EntryFormListingTest entryListing;
    private sp.panelcomponent.EntryFormQuestTest entryQuest;
    private sp.view.LoginPanel loginPanel1;
    private sp.view.Panel panel1;
    // End of variables declaration//GEN-END:variables

    private void setControllerSave() {
        B1 b1 = new B1();
        B2 b2 = new B2();
        B3 b3 = new B3();
        B4 b4 = new B4();
        B5 b5 = new B5();
        Sisipan ssp = new Sisipan();
        Hal1 hal1 = getEntryQuest().getHal11();
        Hal2 hal2 = getEntryQuest().getHal21();
        Hal3 hal3 = getEntryQuest().getHal31();
        Hal4 hal4 = getEntryQuest().getHal41();
        Hal5 hal5 = getEntryQuest().getHal51();
        Hal6 hal6 = getEntryQuest().getHal61();
        Hal7 hal7 = getEntryQuest().getHal71();
        JTable errorTable = getEntryQuest().getErrorTable1().getTabelError();
        SaveController save = new SaveController(b1, b2, b3, b4, b5, ssp, hal1, hal2, hal3, hal4, hal5, hal6, hal7, MainPanel, errorTable);
        entryQuest.getSaveBtn().addActionListener(save);
        ErrorControl.resetErr();
    }
    
    private void setSaveCtrlListing() {
        Hal1Listing halL1 = getEntryListing().getHal1Listing1();
        Hal2Listing halL2 = getEntryListing().getHal2Listing1();
        Dsartb1 db1 = new Dsartb1();
        Dsartb2 db2 = new Dsartb2();
        Dsartb3 db3 = new Dsartb3();
        ArrayList<Dsartb4> db4 = new ArrayList<>();

        JTable errTab = getEntryListing().getErrorTable2().getTabelError();
        SaveCtrlListing save = new SaveCtrlListing(db1, db2, db3, db4, halL1, halL2, MainPanel, errTab);
        entryListing.getSaveBtn().addActionListener(save);
    }

    private void setLoginController() {
        controller = new LoginController(panel1, MainPanel, getLoginPanel1());
        loginPanel1.getPassword1().addKeyListener(controller);
        loginPanel1.getLoginButton1().addActionListener(controller);
    }

    private void setLoadToFormController() {
        UpdateController21 updateController = new UpdateController21(MainPanel, getEntryQuest(), panel1.getUpdateQuest1());
        getPanel1().getUpdateQuest1().getNextButton1().addActionListener(updateController);
        entryQuest.getCloseBtn().setEnabled(false);
    }

    private void entryDariNol() {
        entryQuest.getSaveBtn().setEnabled(true);
        entryQuest.getUpdateBtn().setEnabled(false);
        //FormControl.clearAll();
        FormControl.getController().first();
        controller.show("entryQuest");
        entryQuest.getCloseBtn().setEnabled(true);
    }

    private void setUpdateController() {
        B1 b1 = new B1();
        B2 b2 = new B2();
        B3 b3 = new B3();
        B4 b4 = new B4();
        B5 b5 = new B5();
        Sisipan ssp = new Sisipan();
        UpdatingController uc = new UpdatingController(b1, b2, b3, b4, b5, ssp,
                getEntryQuest().getHal11(),
                getEntryQuest().getHal21(),
                getEntryQuest().getHal31(),
                getEntryQuest().getHal41(),
                getEntryQuest().getHal51(),
                getEntryQuest().getHal61(),
                getEntryQuest().getHal71(),
                MainPanel, getEntryQuest().getErrorTable1().getTabelError());
        getEntryQuest().getUpdateBtn().addActionListener(uc);
    }
}
